<!-- src/components/AlbumEditPopup/index.vue -->
<template>
    <!-- 组件的根元素就是这个 van-popup -->
    <van-popup
        v-model:show="showPopup"
        position="bottom"
        :style="{ height: '60vh' }"
        closeable
        @close="handleClose"
    >
        <van-nav-bar
            :title="popupTitle"
            left-arrow
            @click-left="handleClose"
            @click-right="handleSubmit"
        >
            
        </van-nav-bar>

        <van-form ref="formRef" class="form-container" @submit="handleSubmit">
            <van-cell-group inset border>
                <van-field
                    v-model="formData.title"
                    name="title"
                    label="相册名称"
                    placeholder="请输入相册名称"
                    :rules="rules.title"
                    required
                />
                
                <van-field name="cover" label="相册封面" :rules="rules.cover" required>
                    <template #input>
						<van-uploader
						  v-model="imageList"
						  accept="image/*"
						  :max-count="1"
						  :after-read="handleImageUpload"
						  :preview-full-image="true"
						  upload-text="上传图片"
						/>
                        <!-- <upload-image @success="getUpLoadImage"></upload-image> -->
                    </template>
                </van-field>

                <van-field
                    v-model="formData.desc"
                    name="desc"
                    rows="3"
                    autosize
                    label="相册描述"
                    type="textarea"
                    maxlength="200"
                    placeholder="请输入相册描述"
                    show-word-limit
                />
            </van-cell-group>
        </van-form>
    </van-popup>
</template>

<script lang="ts" setup>
import { ref, reactive, computed } from 'vue'
import type { UploaderFileListItem, FormInstance } from 'vant';
import UploadImage from '@/components/upLoadImage/index.vue'; // 假设你把上面的代码保存在 components/UploadImage.vue


// 1. 定义组件要触发的事件
const emit = defineEmits(['success', 'close'])

const formRef = ref<FormInstance>();
const showPopup = ref(false);
const mode = ref('add');
const isSubmitting = ref(false);

const popupTitle = computed(() => {
    return mode.value === 'edit' ? '编辑相册' : '新增相册';
});

const fileList = ref<UploaderFileListItem[]>([]);
const formData = reactive({ title: '', cover: '', desc: '' });
let albumId: string | number | null = null;

const rules = {
    title: [{ required: true, message: '请输入相册名称' }],
    cover: [{ required: true, message: '请上传相册封面' }],
};

const handleSubmit = async () => {
    try {
        isSubmitting.value = true;
        await formRef.value?.validate();
        
        if (mode.value === 'edit') {
            await apiAlbumEdit({ ...formData, id: albumId });
        } else {
            await apiAlbumAdd(formData);
        }
        
        uni.showToast({
			title: '操作成功',
			icon: 'none',
			duration: 1000
		});
        showPopup.value = false;
        // 2. 触发 success 事件，通知父组件
        emit('success'); 
    } catch (error) {
        console.error('表单验证或提交失败', error);
    } finally {
        isSubmitting.value = false;
    }
};

const handleClose = () => {
    showPopup.value = false;
    emit('close');
};

const open = (type = 'add') => {
    mode.value = type;
    formRef.value?.resetValidation();
    if (type === 'add') {
        albumId = null;
        Object.assign(formData, { title: '', cover: '', desc: '' });
        fileList.value = [];
    }
    showPopup.value = true;
};

const setFormData = (data: Record<string, any>) => {
    Object.keys(formData).forEach(key => {
        if (data[key] !== null && data[key] !== undefined) {
            (formData as any)[key] = data[key];
        }
    });
    
    if (data.id) albumId = data.id;

    if (data.cover) {
        fileList.value = [{ url: data.cover, isImage: true }];
    } else {
        fileList.value = [];
    }
};

// // ... 文件上传逻辑和之前一样 ...
// const upLoadUrl = import.meta.env.VITE_APP_BASE_URL + '/api/upload/image';
// const beforeAvatarUpload = (file: File | File[]) => { /* ... */ return true; };
// const handleAfterRead = (file: UploaderFileListItem | UploaderFileListItem[]) => { /* ... */ };
// const handleDeleteImage = () => { /* ... */ };


// 3. 暴露方法给父组件
defineExpose({
    open,
    setFormData
});


// 获取上传数据
const getUpLoadImage = (item) => {
	if(item != null && item != undefined && item != ''){
		formData.value.avatar = item
	}
}


// 类型定义
interface UploadFile {
  url: string
  name?: string
  status?: 'uploading' | 'done' | 'failed'
  message?: string
  type?: string
  file?: File
}
// 图片和视频列表
const imageList = ref<UploadFile[]>([])
// 图片上传逻辑
const handleImageUpload = async (file: any) => {
  const rawFile = file.file
  const formData = new FormData()
  formData.append('file', rawFile)

  try {
    Toast.loading('上传中...')
    const res = await uploadToServer(formData) // 调用你自己的上传接口
    file.status = 'done'
    file.url = res.data.url
    Toast.clear()
  } catch (err) {
    file.status = 'failed'
    file.message = '上传失败'
    Toast.fail('图片上传失败')
  }
}
</script>

<style scoped>
.form-container {
    padding-top: 16px;
}
</style>